# -*- coding: utf-8 -*-
"""
@Time: 2024/10/14 15:49
@File: 聚水潭 - jst_open_api.py
@IDE: PyCharm
@Auth: Kendrick.Kc.Guan
@Email: 509556985@qq.com
@Version: 1.0
"""


import json
import time
import hashlib
import requests
import traceback
from collections import OrderedDict


class JuShuiTanOpenPlatformApi:
    """
    聚水潭开放平台自有商城API接口集合
    聚水潭开放平台Key、Secret:
        - APP Key - 70660b319bcf45af9bf01522387a5cc5
        - APP Secret - 77bfcc42299543969eef429dfe9851e8
    业务接口授权信息
        - access_token - 7f40378edd63453d8b9b95fe9ee78898;
        - refresh_token - 17956775f67e4cee827de836b4bd4b66;
        - expires_in - 31104000
    """

    # url = 'https://openapi.jushuitan.com'
    # app_key = '70660b319bcf45af9bf01522387a5cc5'
    # app_secret = '77bfcc42299543969eef429dfe9851e8'

    def __init__(self
                 , url: str = 'https://openapi.jushuitan.com'
                 , app_key: str = '70660b319bcf45af9bf01522387a5cc5'
                 , app_secret: str = '77bfcc42299543969eef429dfe9851e8'
                 ):
        self.url = url
        self.app_key = app_key
        self.app_secret = app_secret
        self.headers = {"Content-Type": "application/json"}
        self.sub_sign = {
            "app_key": self.app_key,
            "charset": "utf-8",
            "code": f"Kc{str(time.time())[-4:]}",
            "grant_type": "authorization_code",
            "timestamp": self.get_timestamp(),
        }
        self.token = {'access_token': None, 'sign': None}
        self.get_token()

    def request_api(self, method: str = "POST", **kwargs):
        """
        封装requests.post请求
        :param method: 请求类型，默认为POST
        :param kwargs: 其它参数
        :return: requests库的Response对象
        """
        time.sleep(1)
        try:
            response = requests.request(method, headers=self.headers, **kwargs['kwargs'])
            # response.raise_for_status()  # 如果响应状态码不是200，抛出异常
            # if response.json()['code'] != 0:
            #     raise Exception(f"{kwargs['kwargs']} \n 接口返回错误, 错误信息：{response.json()}")
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"{kwargs['kwargs']} 请求发生错误: {traceback.print_exc()}")

    @staticmethod
    def get_timestamp():
        """
        获取当前10位时间戳
        :return:
        """
        return int(time.time())

    def get_sign(self, data):
        """
        自有商城获取sign签名
        :param data: self.sub_sign
        :return: sign
        """
        list_data = list(data.keys())
        string_sign = self.app_secret
        sort_list = sorted(list_data)

        for item in sort_list:
            string_sign += str(item)
            string_sign += str(data[item])
        sign = hashlib.md5(string_sign.encode('utf-8')).hexdigest()
        return sign

    def get_token(self, api:str = "/openWeb/auth/getInitToken"):
        """
        自有商城获取token
        :param api: 请求地址
        :return:
        """
        self.sub_sign['sign'] = self.get_sign(self.sub_sign)
        urlencoded_data = requests.compat.urlencode(self.sub_sign)
        kwargs = {'url': f"{self.url}{api}?{urlencoded_data}"}
        self.token['access_token'] = self.request_api(kwargs=kwargs)['data']['access_token']
        self.token['sign'] = self.sub_sign['sign']
        return self.token

    def call(self, api:str, biz:dict = None):
        """
        调用业务接口
        :param api: 请求地址
        :param biz: 业务参数
        :return:
        """
        params = OrderedDict()
        params['app_key'] = self.app_key
        params['access_token'] = self.token['access_token']
        params['timestamp'] = self.get_timestamp()
        params['version'] = '2'
        params['charset'] = 'utf-8'
        params['biz'] =  json.dumps(biz)
        params['sign'] = self.get_sign(params)
        self.headers = {'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'}
        kwargs = OrderedDict()
        kwargs['url'] = self.url + api
        kwargs['data'] = params
        result = self.request_api(kwargs=kwargs)
        return result

